package com.ruoyi.system.controller;

import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.uuid.UUID;
import com.ruoyi.system.service.IWechatLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * 微信扫码登录Controller
 *
 * @author ChenYF
 * @date 2025-09-11 8:56
 */
@RestController
@RequestMapping("/wechat/login")
public class WechatLoginController {

    @Autowired
    private IWechatLoginService wechatLoginService;

    /**
     * 生成微信扫码登录二维码
     */
    @GetMapping("/qrcode")
    public R<Map<String, String>> generateQRCode() {
        String state = UUID.randomUUID().toString();
        Map<String, String> result = wechatLoginService.generateQRCode(state);
        return R.ok(result);
    }

    /**
     * 轮询检查扫码状态
     */
    @GetMapping("/check/{state}")
    public R<Map<String, Object>> checkLoginStatus(@PathVariable String state) {
        Map<String, Object> result = wechatLoginService.checkLoginStatus(state);
        return R.ok(result);
    }

    /**
     * 微信扫码回调地址
     */
    @GetMapping("/callback")
    public void wechatCallback(@RequestParam("code") String code,
                               @RequestParam("state") String state,
                               HttpServletResponse response) throws IOException {
        // 处理微信回调
        wechatLoginService.processWechatCallback(code, state);

        // 重定向到前端页面，前端会通过轮询获取登录状态
        response.sendRedirect("/wechat/login/success");
    }

    /**
     * 登录成功页面
     */
    @GetMapping("/success")
    public void loginSuccess(HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write("<!DOCTYPE html><html><head><title>登录成功</title></head><body><h2>微信扫码登录成功，页面即将跳转...</h2><script>window.close();</script></body></html>");
    }
}
